package edu.rakovic.elearning.pages;

import java.util.Collection;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;

import edu.rakovic.elearning.beans.ApplicationBean;
import edu.rakovic.elearning.enums.Role;
import edu.rakovic.elearning.exceptions.RedudantAppliacationException;
import edu.rakovic.elearning.interfaces.Application;
import edu.rakovic.elearning.interfaces.Course;
import edu.rakovic.elearning.interfaces.User;
import edu.rakovic.elearning.service.Applications;
import edu.rakovic.elearning.service.Courses;

public class ViewCourses {
	
	@Inject
	@Property
	private Courses courses;
	
	@Property
	private Course currentCourse;
	
	@Inject
	@Property
	private Applications applications;
	
	@InjectPage
	private Info infoPage;
	
	
	
	
	
	// Event handler for action link - apply to course
	Object onActionFromApply(String courseName) {
		Course course = courses.retreiveSingleCourse(courseName);
		Application application = new ApplicationBean();
	//	boolean applied = false;
		try {
			application.applyCourse(user, course);
		} catch (RedudantAppliacationException e) {
			//e.printStackTrace();
			System.out.println(e.getMessage());
			infoPage.setMessage(e.getMessage());
			return infoPage;
		}
			applications.save(application);
			return ViewStudentApplications.class;
		
	}
	
	// login check
	@SessionState
	private User user;

	private boolean userExists;
	
	public User getUser() {
		return user;
	}
	
	Object onActivate() {
		if (!userExists) return Login.class;
		if (userExists && user.getRole() != Role.STUDENT) return Index.class;
		return null;
	}
	

}
